package com.chianghao.rock.system.controller;

import java.util.List;
import java.util.stream.Collectors;

import javax.validation.constraints.NotNull;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.chianghao.core.web.R;
import com.chianghao.rock.admin.system.role.vo.RoleVo;
import com.chianghao.rock.admin.system.user_role.dto.UserRoleDto;
import com.chianghao.rock.common.SequenceService;
import com.chianghao.rock.system.entity.Role;
import com.chianghao.rock.system.service.user_role.UserRoleService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;


@RestController
@RequestMapping("system/user-role")
@Api(value="用户角色",tags={"用户角色"})
public class UserRoleController {

    @Autowired
    UserRoleService userRoleService;

    @Autowired
    SequenceService sequenceService;

	@PostMapping("save")
	@ApiOperation("保存用户和角色的关系")
	public R<Boolean> sava(@Validated @RequestBody UserRoleDto dto) {
		userRoleService.doSaveRelation(dto.getUserId(),dto.getRoleIds());
		return R.getSuccess(true);
	}


    @GetMapping("query-role")
    @ApiOperation("查询用户的已有角色")
    @ApiImplicitParam(name="userId",value = "用户ID",paramType = "query",required = true,dataType = "String")
    public R<List<RoleVo>> query(@NotNull(message="error:user.id,not.null") Long userId) {
    	List<Role> List = userRoleService.queryByUserId(userId);
    	return R.getSuccess(toRoleListVo(List));
    }


    private RoleVo toRoleVo(Role role) {
    	RoleVo vo = new RoleVo();
    	BeanUtils.copyProperties(role, vo);
    	return vo;
    }
    
	private List<RoleVo> toRoleListVo(List<Role> list) {
		return list.stream().map(item->toRoleVo(item)).collect(Collectors.toList());
	}

    
    
    

}